package com.sang.config;

import com.sang.pojo.User;
import com.sang.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权        操作在ShiroConfig
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法：doGetAuthorizationInfo");
        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登陆的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();//拿到User
        info.addStringPermission(currentUser.getPerms());//拿到user的授权

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证方法：doGetAuthorizationInfo");
        //用户名 密码   数据库取
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        User user = userService.queryUserByName(userToken.getUsername());
        if(user==null) {//没有这个人
            return null; //抛出异常  UnknownAccountException
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);
        //可以加密      MD5加密       MD5盐值加密
        //密码认证，shiro做~  密码是加密过的
        return new SimpleAuthenticationInfo("",user.getPwd(),"");
    }
}
